package com.shenda.device;

import java.util.concurrent.CountDownLatch;

import com.shenda.device.message.ReqMsg_GetMac;
import com.swak.codec.Hex;
import com.swak.rxtx.Channels;
import com.swak.rxtx.channel.Channel;
import com.swak.rxtx.channel.ChannelHandler;
import com.swak.rxtx.codec.FixedLengthFrameDecoder;

import io.netty.buffer.ByteBuf;

public class Heartbeats {

	public static void main(String[] args) throws Exception {

		// 创建处理器
		Channels.builder().setWorks(2).setHeartbeatSeconds(10).setChannelInit((channel) -> {
			// 先设置命令的固定长度是10
			channel.pipeline().add(new FixedLengthFrameDecoder(18));
			channel.pipeline().add(new ChannelHandler() {
				@Override
				public void read(Channel channel, Object data) {
					ByteBuf buf = (ByteBuf) data;
					byte[] command = new byte[buf.readableBytes()];
					buf.readBytes(command);
					System.out.println(new String(Hex.encodeHex(command, false)));
					buf.release();
				}

				@Override
				public void heartbeat(Channel channel) {
					super.heartbeat(channel);
					channel.write(ReqMsg_GetMac.of().encode());
				}
			});
		}).build();

		// 系统不退出
		CountDownLatch latch = new CountDownLatch(1);
		latch.await();
	}
}
